<?php
header('Content-Type: text/html; charset=utf-8');

// 数据库连接配置
$config = [
    'type' => 'mysql',
    'hostname' => '127.0.0.1',
    'database' => 'dev002_gxyusheng',
    'username' => 'root',
    'password' => '159456',
    'charset' => 'utf8mb4',
    'prefix' => 'fa_'
];
// 获取搜索值
$search = $_GET['search'] ?? '';
$startDate = $_GET['start_date'] ?? date('Y-m-d');
try {
    // 创建数据库连接
    $dsn = "{$config['type']}:host={$config['hostname']};dbname={$config['database']};charset={$config['charset']}";
    $pdo = new PDO($dsn, $config['username'], $config['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4",
        PDO::ATTR_TIMEOUT => 5 // 设置数据库连接超时
    ]);

    // 获取筛选参数
    $statusFilter = $_GET['status'] ?? 'paid';  // 默认显示已支付
    $startDate = $_GET['start_date'] ?? '';  // 默认不选日期
    $page = $_GET['page'] ?? 1;  // 分页参数
    $limit = 2000;  // 每页显示20条记录
    $offset = ($page - 1) * $limit;
    
    // 检查是否是清除日期操作
    $isClearDate = isset($_GET['clear_date']) && $_GET['clear_date'] == '1';
    
    // 构建SQL查询条件
    $whereConditions = [];
    $params = [];
    
    // 日期筛选条件 - 如果选择了日期才添加
    if (!empty($startDate)) {
        $whereConditions[] = "f.create_time >= :start_date";
        $params[':start_date'] = $startDate;
    }

     if($search){
        $whereConditions[] = " c.name LIKE :search";
        $params[':search'] = "%$search%";
    }

    // 状态筛选条件
    if ($statusFilter === 'paid') {
        $whereConditions[] = "(o.pay_status = 1 AND o.refund_status IS NULL)";
    } elseif ($statusFilter === 'waiting') {
        $whereConditions[] = "f.status = 0";
    } elseif ($statusFilter === 'refunded') {
        $whereConditions[] = "(o.refund_status = 1 OR o.pay_status = 4)";
    } elseif ($statusFilter === 'expired') {
        $whereConditions[] = "f.status = 5";
    } else {
        // 显示全部状态（已支付、未缴费、过期未缴费、退款）
        $whereConditions[] = "(o.pay_status = 1 OR o.pay_status = 4 OR f.status = 0 OR f.status = 5)";
    }
    
    // 日期筛选条件已经在基础条件中添加
    
    // 查询总记录数（用于分页）
    $countSql = "SELECT COUNT(*) as total 
                FROM `eb_apply_form_item` as f 
                LEFT JOIN fa_user u ON f.user_id = u.id 
                LEFT JOIN eb_classes c ON c.id = f.classes_id 
                LEFT JOIN fa_order o ON o.id = f.order_id 
                WHERE " . implode(" AND ", $whereConditions);
    
    $countStmt = $pdo->prepare($countSql);
    foreach ($params as $key => $value) {
        $countStmt->bindValue($key, $value);
    }
    $countStmt->execute();
    $totalRecords = $countStmt->fetch()['total'];
    $totalPages = ceil($totalRecords / $limit);
    
    // 执行查询 - 包含多种状态：已支付、未缴费、过期未缴费、退款（带分页）
    $sql = "SELECT 
                f.intro, 
                c.name as class_name, 
                u.username,
                r.name as nickname, 
                r.id_card,
                u.mobile, 
                f.table_id, 
                f.amount, 
                f.create_time, 
                o.pay_status, 
                o.refund_status, 
                o.refund_amount,
                o.pay_channel_id,
                o.id as order_id,
                f.status as form_status
            FROM `eb_apply_form_item` as f 
            LEFT JOIN fa_user u ON f.user_id = u.id 
            LEFT JOIN eb_classes c ON c.id = f.classes_id 
            LEFT JOIN fa_order o ON o.id = f.order_id 
            left join fa_registration r on r.user_id = u.id and id_card is not null
            WHERE " . implode(" AND ", $whereConditions) . "
            ORDER BY f.create_time DESC
            LIMIT $limit OFFSET $offset";

    $stmt = $pdo->prepare($sql);
    
    // 绑定参数
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    
    $stmt->execute();
    $records = $stmt->fetchAll();

    // 计算统计数据 - 需要查询所有符合条件的记录，不限于当前筛选状态
    $statsSql = "SELECT 
                    f.amount, 
                    o.pay_status, 
                    o.refund_status, 
                    o.refund_amount,
                    f.status as form_status,
                    f.user_id,
                    f.create_time
                FROM `eb_apply_form_item` as f 
                LEFT JOIN fa_order o ON o.id = f.order_id 
                WHERE (o.pay_status = 1 OR o.pay_status = 4 OR f.status = 0 OR f.status = 5)";
    
    // 如果选择了日期，添加日期条件
    if (!empty($startDate)) {
        $statsSql .= " AND f.create_time >= :start_date";
    }
    
    $statsStmt = $pdo->prepare($statsSql);
    if (!empty($startDate)) {
        $statsStmt->bindValue(':start_date', $startDate);
    }
    $statsStmt->execute();
    $allRecords = $statsStmt->fetchAll();
    
    // 查询当日报名人数和缴费人数（同一个用户只算一个）
    // 如果用户选择了日期，则使用该日期；否则使用当前日期
    // 如果是清除日期操作，则使用当前日期进行当日统计
    $targetDate = (!empty($startDate) && !$isClearDate) ? $startDate : date('Y-m-d');
    $todaySignupSql = "SELECT COUNT(*) as count 
                       FROM (
                           SELECT MAX(id) as max_id
                           FROM `eb_apply_form_item` 
                           WHERE DATE(create_time) = :today
                           GROUP BY user_id
                       ) as last_records";
    $todaySignupStmt = $pdo->prepare($todaySignupSql);
    $todaySignupStmt->bindValue(':today', $targetDate);
    $todaySignupStmt->execute();
    $todaySignupCount = $todaySignupStmt->fetch()['count'];
    
    // 独立总计统计（不受任何筛选条件影响）
    // 总缴费金额
    $totalPaidAmountSql = "SELECT SUM(o.amount) as total_amount 
                          FROM `eb_apply_form_item` as f 
                          LEFT JOIN fa_order o ON o.id = f.order_id 
                          WHERE o.pay_status = 1 AND o.refund_status IS NULL";
    $totalPaidAmountStmt = $pdo->prepare($totalPaidAmountSql);
    $totalPaidAmountStmt->execute();
    $totalPaidAmount = $totalPaidAmountStmt->fetch()['total_amount'] ?? 0;
    
    // 已支付笔数
    $totalPaidCountSql = "SELECT COUNT(*) as count 
                         FROM `eb_apply_form_item` as f 
                         LEFT JOIN fa_order o ON o.id = f.order_id 
                         WHERE o.pay_status = 1 AND o.refund_status IS NULL";
    $totalPaidCountStmt = $pdo->prepare($totalPaidCountSql);
    $totalPaidCountStmt->execute();
    $totalPaidCount = $totalPaidCountStmt->fetch()['count'] ?? 0;
    
    // 未缴费笔数
    $totalWaitingCountSql = "SELECT COUNT(*) as count 
                            FROM `eb_apply_form_item` as f 
                            LEFT JOIN fa_order o ON o.id = f.order_id 
                            WHERE f.status = 0";
    $totalWaitingCountStmt = $pdo->prepare($totalWaitingCountSql);
    $totalWaitingCountStmt->execute();
    $totalWaitingCount = $totalWaitingCountStmt->fetch()['count'] ?? 0;
    
    // 过期未缴笔数
    $totalExpiredCountSql = "SELECT COUNT(*) as count 
                             FROM `eb_apply_form_item` as f 
                             LEFT JOIN fa_order o ON o.id = f.order_id 
                             WHERE f.status = 5";
    $totalExpiredCountStmt = $pdo->prepare($totalExpiredCountSql);
    $totalExpiredCountStmt->execute();
    $totalExpiredCount = $totalExpiredCountStmt->fetch()['count'] ?? 0;
    
    // 已退款笔数
    $totalRefundedCountSql = "SELECT COUNT(*) as count 
                             FROM `eb_apply_form_item` as f 
                             LEFT JOIN fa_order o ON o.id = f.order_id 
                             WHERE o.refund_status = 1 OR o.pay_status = 4";
    $totalRefundedCountStmt = $pdo->prepare($totalRefundedCountSql);
    $totalRefundedCountStmt->execute();
    $totalRefundedCount = $totalRefundedCountStmt->fetch()['count'] ?? 0;
    
    // 总记录笔数
    $totalRecordsCountSql = "SELECT COUNT(*) as count 
                            FROM `eb_apply_form_item` as f 
                            LEFT JOIN fa_order o ON o.id = f.order_id";
    $totalRecordsCountStmt = $pdo->prepare($totalRecordsCountSql);
    $totalRecordsCountStmt->execute();
    $totalRecordsCount = $totalRecordsCountStmt->fetch()['count'] ?? 0;
    
    // 总退款金额
    $totalRefundAmountSql = "SELECT SUM(o.refund_amount) as total_refund 
                            FROM `eb_apply_form_item` as f 
                            LEFT JOIN fa_order o ON o.id = f.order_id 
                            WHERE o.refund_status = 1 OR o.pay_status = 4";
    $totalRefundAmountStmt = $pdo->prepare($totalRefundAmountSql);
    $totalRefundAmountStmt->execute();
    $totalRefundAmount = $totalRefundAmountStmt->fetch()['total_refund'] ?? 0;
    
    $todayPaidSql = "SELECT COUNT(DISTINCT f.user_id) as count 
                     FROM `eb_apply_form_item` as f 
                     LEFT JOIN fa_order o ON o.id = f.order_id 
                     WHERE DATE(f.create_time) = :today 
                     AND o.pay_status = 1 
                     AND o.refund_status is null";
    $todayPaidStmt = $pdo->prepare($todayPaidSql);
    $todayPaidStmt->bindValue(':today', $targetDate);
    $todayPaidStmt->execute();
    $todayPaidCount = $todayPaidStmt->fetch()['count'];
    
    // 新增：当日缴费金额统计
    $todayPaidAmountSql = "SELECT SUM(o.amount) as total_amount 
                           FROM `eb_apply_form_item` as f 
                           LEFT JOIN fa_order o ON o.id = f.order_id 
                           WHERE DATE(f.create_time) = :today 
                           AND o.pay_status = 1 
                           AND o.refund_status is null";
    $todayPaidAmountStmt = $pdo->prepare($todayPaidAmountSql);
    $todayPaidAmountStmt->bindValue(':today', $targetDate);
    $todayPaidAmountStmt->execute();
    $todayPaidAmount = $todayPaidAmountStmt->fetch()['total_amount'] ?? 0;
    
    // 新增：当日退费人数统计
    $todayRefundCountSql = "SELECT COUNT(DISTINCT f.user_id) as count 
                           FROM `eb_apply_form_item` as f 
                           LEFT JOIN fa_order o ON o.id = f.order_id 
                           WHERE DATE(f.create_time) = :today 
                           AND (o.refund_status = 1 OR o.pay_status = 4)";
    $todayRefundCountStmt = $pdo->prepare($todayRefundCountSql);
    $todayRefundCountStmt->bindValue(':today', $targetDate);
    $todayRefundCountStmt->execute();
    $todayRefundCount = $todayRefundCountStmt->fetch()['count'];
    
    // 新增：当日退费金额统计
    $todayRefundAmountSql = "SELECT SUM(o.refund_amount) as total_refund 
                            FROM `eb_apply_form_item` as f 
                            LEFT JOIN fa_order o ON o.id = f.order_id 
                            WHERE DATE(f.create_time) = :today 
                            AND (o.refund_status = 1 OR o.pay_status = 4)";
    $todayRefundAmountStmt = $pdo->prepare($todayRefundAmountSql);
    $todayRefundAmountStmt->bindValue(':today', $targetDate);
    $todayRefundAmountStmt->execute();
    $todayRefundAmount = $todayRefundAmountStmt->fetch()['total_refund'] ?? 0;
    
    // 获取最近10天的统计数据
    $last10DaysStats = [];
    for ($i = 9; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        
        // 报名人数（去重）
        $signupSql = "SELECT COUNT(DISTINCT user_id) as count 
                     FROM `eb_apply_form_item` 
                     WHERE DATE(create_time) = :date";
        $signupStmt = $pdo->prepare($signupSql);
        $signupStmt->bindValue(':date', $date);
        $signupStmt->execute();
        $signupCount = $signupStmt->fetch()['count'] ?? 0;
        
        // 缴费人数（去重）
        $paidSql = "SELECT COUNT(DISTINCT f.user_id) as count 
                   FROM `eb_apply_form_item` as f 
                   LEFT JOIN fa_order o ON o.id = f.order_id 
                   WHERE DATE(f.create_time) = :date 
                   AND o.pay_status = 1 
                   AND o.refund_status IS NULL";
        $paidStmt = $pdo->prepare($paidSql);
        $paidStmt->bindValue(':date', $date);
        $paidStmt->execute();
        $paidCount = $paidStmt->fetch()['count'] ?? 0;
        
        // 退费人数（去重）
        $refundSql = "SELECT COUNT(DISTINCT f.user_id) as count 
                     FROM `eb_apply_form_item` as f 
                     LEFT JOIN fa_order o ON o.id = f.order_id 
                     WHERE DATE(f.create_time) = :date 
                     AND (o.refund_status = 1 OR o.pay_status = 4)";
        $refundStmt = $pdo->prepare($refundSql);
        $refundStmt->bindValue(':date', $date);
        $refundStmt->execute();
        $refundCount = $refundStmt->fetch()['count'] ?? 0;
        
        // 报名金额
        $signupAmountSql = "SELECT SUM(amount) as total 
                           FROM `eb_apply_form_item` 
                           WHERE DATE(create_time) = :date";
        $signupAmountStmt = $pdo->prepare($signupAmountSql);
        $signupAmountStmt->bindValue(':date', $date);
        $signupAmountStmt->execute();
        $signupAmount = $signupAmountStmt->fetch()['total'] ?? 0;
        
        // 缴费金额
        $paidAmountSql = "SELECT SUM(o.amount) as total 
                         FROM `eb_apply_form_item` as f 
                         LEFT JOIN fa_order o ON o.id = f.order_id 
                         WHERE DATE(f.create_time) = :date 
                         AND o.pay_status = 1 
                         AND o.refund_status IS NULL";
        $paidAmountStmt = $pdo->prepare($paidAmountSql);
        $paidAmountStmt->bindValue(':date', $date);
        $paidAmountStmt->execute();
        $paidAmount = $paidAmountStmt->fetch()['total'] ?? 0;
        
        // 退费金额
        $refundAmountSql = "SELECT SUM(o.refund_amount) as total 
                           FROM `eb_apply_form_item` as f 
                           LEFT JOIN fa_order o ON o.id = f.order_id 
                           WHERE DATE(f.create_time) = :date 
                           AND (o.refund_status = 1 OR o.pay_status = 4)";
        $refundAmountStmt = $pdo->prepare($refundAmountSql);
        $refundAmountStmt->bindValue(':date', $date);
        $refundAmountStmt->execute();
        $refundAmount = $refundAmountStmt->fetch()['total'] ?? 0;
        
        $last10DaysStats[] = [
            'date' => $date,
            'signup_count' => $signupCount,
            'paid_count' => $paidCount,
            'refund_count' => $refundCount,
            'signup_amount' => $signupAmount,
            'paid_amount' => $paidAmount,
            'refund_amount' => $refundAmount
        ];
    }
    
    // 查询所有记录（不受日期筛选影响，只受状态筛选影响）
    $allStatsSql = "SELECT f.*, o.pay_status, o.refund_status, o.amount, o.refund_amount, f.status as form_status
                   FROM `eb_apply_form_item` as f 
                   LEFT JOIN fa_order o ON o.id = f.order_id 
                   WHERE 1=1";
    $allStatsParams = [];
    
    // 添加状态筛选条件
    if (!empty($statusFilter)) {
        if ($statusFilter === 'paid') {
            $allStatsSql .= " AND o.pay_status = 1 AND o.refund_status IS NULL";
        } elseif ($statusFilter === 'waiting') {
            $allStatsSql .= " AND f.status = 0";
        } elseif ($statusFilter === 'refunded') {
            $allStatsSql .= " AND (o.refund_status = 1 OR o.pay_status = 4)";
        } elseif ($statusFilter === 'expired') {
            $allStatsSql .= " AND f.status = 5";
        }
    }
    
    $allStatsStmt = $pdo->prepare($allStatsSql);
    $allStatsStmt->execute($allStatsParams);
    $allStatsRecords = $allStatsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 初始化统计变量
    $totalAmount = 0;
    $totalRecords = 0;
    $totalRefund = 0;
    $totalPaid = 0;
    $totalWaiting = 0;
    $totalExpired = 0;
    $totalRefunded = 0;
    
    foreach ($allStatsRecords as $record) {
        $totalRecords++;
        
        // 根据状态分类统计
        if ($record['refund_status'] == 1 || $record['pay_status'] == 4) {
            $totalRefunded++;
            $totalRefund += $record['refund_amount'];
        } elseif ($record['pay_status'] == 1 && $record['refund_status'] == null) {
            // 只统计有效已支付且没有退款的记录
            $totalPaid++;
            $totalAmount += $record['amount'];
        } elseif ($record['form_status'] == 0) {
            $totalWaiting++;
        } elseif ($record['form_status'] == 5) {
            $totalExpired++;
        }
    }

} catch (PDOException $e) {
    die("数据库连接错误: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>缴费记录查询 - 手机版</title>
    
    <!-- 资源预加载和DNS预解析 - 使用更稳定的CDN -->
    <link rel="dns-prefetch" href="//cdnjs.cloudflare.com">
    <link rel="preconnect" href="https://cdnjs.cloudflare.com">
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.10.0/font/bootstrap-icons.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <noscript>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    </noscript>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.js"></script>
    <script>
        // Chart.js 加载失败时的本地回退
        if (typeof Chart === 'undefined') {
            document.write('<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js"><\/script>');
        }
    </script>
    <!-- 添加额外的Chart.js回退源 -->
    <script>
        // 等待页面加载完成后检查Chart.js
        window.addEventListener('load', function() {
            if (typeof Chart === 'undefined') {
                console.warn('主Chart.js加载失败，尝试备用源...');
                const script = document.createElement('script');
                script.src = 'https://unpkg.com/chart.js@4.4.0/dist/chart.umd.js';
                script.onload = function() {
                    console.log('备用Chart.js加载成功');
                };
                script.onerror = function() {
                    console.error('所有Chart.js源都加载失败');
                };
                document.head.appendChild(script);
            }
        });
    </script>
    <style>
        /* 移动端优化样式 */
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            font-size: 14px;
            line-height: 1.4;
            padding-bottom: 20px;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }
        
        /* 预加载关键CSS */
        .stats-card, .btn, .table {
            will-change: transform, opacity;
        }
        
        /* 减少重绘和重排 */
        .stats-card {
            transform: translateZ(0);
            backface-visibility: hidden;
        }
        
        /* 优化动画性能 */
        .spinner-border {
            transform: translateZ(0);
        }
        
        .container {
            padding: 10px;
        }
        
        .header {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            padding: 15px;
            margin-bottom: 15px;
        }
        
        .header h1 {
            font-size: 1.5rem;
            margin-bottom: 5px;
        }
        
        .header p {
            font-size: 0.9rem;
            margin-bottom: 0;
        }
        
        .card {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            margin-bottom: 15px;
        }
        
        .stats-card {
            padding: 12px;
            text-align: center;
            border-radius: 10px;
            margin-bottom: 10px;
            min-height: 100px;
        }
        
        .stats-card i {
        }
        
        /* 手势图标样式 */
        .hand-gesture {
            position: absolute;
            z-index: 1000;
            font-size: 24px;
            color: #ff6b6b;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
            animation: handPulse 1.5s infinite;
            pointer-events: none;
            transition: all 0.5s ease;
        }
        
        @keyframes handPulse {
            0%, 100% {
                transform: translateY(0) scale(1);
                opacity: 1;
            }
            50% {
                transform: translateY(-10px) scale(1.1);
                opacity: 0.8;
            }
        }
         
         @keyframes handClick {
             0% {
                 transform: scale(1);
             }
             50% {
                 transform: scale(0.8);
             }
             100% {
                 transform: scale(1);
             }
         }
        
        .stats-card i {
            font-size: 1.5rem !important;
            margin-bottom: 5px;
        }
        
        .stats-number {
            font-size: 1.1rem;
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        .stats-card div:last-child {
            font-size: 0.8rem;
            opacity: 0.9;
        }
        
        /* 图表容器优化 */
        .chart-container {
            background: #fff;
            border-radius: 10px;
            padding: 15px;
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.06);
            margin-bottom: 15px;
            height: 250px;
        }
        
        .chart-header h6 {
            font-size: 0.9rem;
            margin-bottom: 10px;
        }
        
        /* 搜索框优化 - 标准化样式 */
        .search-box {
            margin-bottom: 15px;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            border: 1px solid rgba(0, 0, 0, 0.06);
        }
        
        .search-box h5 {
            font-size: 1rem;
            margin-bottom: 12px;
            color: #495057;
            font-weight: 600;
        }
        
        .input-group-lg .input-group-text {
            border-radius: 8px 0 0 8px !important;
        }
        
        .input-group-lg .form-control {
            border-radius: 0 8px 8px 0 !important;
        }
        
        .form-control {
            font-size: 0.9rem;
            padding: 8px 12px;
            border-radius: 8px;
        }
        
        /* 状态筛选按钮优化 */
        .btn {
            font-size: 0.8rem;
            padding: 6px 12px;
            border-radius: 8px;
            margin: 3px;
            min-width: 70px;
        }
        
        .btn-check:checked + .btn {
            transform: scale(1.03);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
        }
        
        /* 表格优化 */
        .table {
            font-size: 0.8rem;
            margin-bottom: 0;
        }
        
        .table th {
            padding: 8px 5px;
            font-weight: 600;
        }
        
        .table td {
            padding: 8px 5px;
            vertical-align: middle;
        }
        
        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
        }
        
        /* 响应式调整 */
        @media (max-width: 576px) {
            .container {
                padding: 8px;
            }
            
            .header {
                padding: 12px;
            }
            
            .header h1 {
                font-size: 1.3rem;
            }
            
            .stats-card {
                min-height: 90px;
                padding: 10px;
            }
            
            .stats-number {
                font-size: 1rem;
            }
            
            .chart-container {
                height: 220px;
                padding: 12px;
            }
            
            .btn {
                font-size: 0.75rem;
                padding: 5px 10px;
                min-width: 60px;
            }
            
            .table {
                font-size: 0.75rem;
            }
        }
        
        /* 移动端触摸优化 */
        .btn:active {
            transform: scale(0.98);
        }
        
        input[type="date"] {
            -webkit-appearance: none;
            min-height: 38px;
        }
        
        /* 滚动条优化 */
        ::-webkit-scrollbar {
            width: 6px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 3px;
        }
        
        /* 加载动画优化 */
        .loading-spinner {
            width: 30px;
            height: 30px;
        }
        
        /* 状态标签优化 */
        .badge {
            font-size: 0.7rem;
            padding: 4px 8px;
            border-radius: 6px;
        }
        
        /* 卡片标题优化 */
        .card-header h5 {
            font-size: 1rem;
            margin-bottom: 0;
        }
        
        /* 表单组优化 */
        .form-group {
            margin-bottom: 12px;
        }
        
        /* 输入框组优化 */
        .input-group .btn {
            min-width: auto;
        }
        
        /* 文本优化 */
        small {
            font-size: 0.75rem;
        }
        
        /* 移动端隐藏某些元素 */
        .mobile-hidden {
            display: none;
        }
        
        /* 移动端显示优化 */
        .mobile-show {
            display: block;
        }
        
        /* 移动端时间显示优化 */
        .mobile-time-show {
            display: table-cell;
            font-size: 0.8rem;
            white-space: nowrap;
            min-width: 70px;
        }
        
        /* 统计卡片选中状态 */
        .stats-card.active {
            box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.5), 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
            transform: translateY(-2px);
            transition: all 0.2s ease-in-out;
        }
        
        @media (min-width: 768px) {
            .mobile-hidden {
                display: table-cell;
            }
            .mobile-show {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="container py-3">
        <!-- 头部 -->
        <div class="header p-3 mb-3 text-center">
            <h1 class="fw-bold text-primary mb-1">
                <i class="bi bi-cash-coin me-2"></i>
                缴费记录查询
            </h1>
            <p class="text-muted">手机版 - 实时查看缴费记录</p>
        </div>

        <!-- 搜索和筛选 -->
        <div class="card mb-3">
            <div class="card-body p-3">
                <form method="GET" action="" id="filterForm">
                    <div class="row">
                        <div class="col-12 mb-3">
                            <div class="search-box">
                                <h5 class="mb-2 text-center"><i class="bi bi-search me-1"></i>快速搜索</h5>
                                <div class="input-group input-group-lg">
                                    <span class="input-group-text bg-primary text-white">
                                        <i class="bi bi-search"></i>
                                    </span>
                                    <input type="text" id="searchInput" name="search" class="form-control" placeholder="搜索姓名、手机号、课程..." value="<?php echo $search; ?>" style="border-left: none;">
                                </div>
                            </div>
                        </div>
                        <div class="col-12 mb-3">
                            <div class="search-box" style="padding: 12px; border-radius: 10px; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border: 1px solid #dee2e6;">
                                <h6 class="mb-2 text-center text-muted" style="font-size: 14px; font-weight: 500;"><i class="bi bi-calendar me-1"></i>日期筛选</h6>
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text bg-info text-white" style="font-size: 12px; padding: 6px 10px;">
                                        <i class="bi bi-calendar"></i>
                                    </span>
                                    <input type="date" name="start_date" class="form-control form-control-sm" value="<?php echo htmlspecialchars($startDate); ?>" min="2025-11-05" max="<?php echo date('Y-m-d'); ?>" style="border-left: none; font-size: 12px; padding: 6px 10px;">
                                    <?php if (!empty($startDate)): ?>
                                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="clearDateAndReset()" title="清除日期" style="padding: 6px 10px; font-size: 12px;">
                                        <i class="bi bi-x-lg"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                                <small class="text-muted mt-2 text-center d-block" style="font-size: 11px;">
                                    <i class="bi bi-info-circle me-1"></i>
                                    <?php echo empty($startDate) ? '日期未选' : '已选: ' . htmlspecialchars($startDate); ?>
                                </small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 状态筛选选项卡 -->
                    <div class="row mt-3">
                        <div class="col-12">
                            <!-- 查询条数显示 -->
                            <div class="text-center mb-3">
                                <div class="alert alert-primary border-0" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 10px; border-radius: 8px;">
                                    <h6 class="mb-0">
                                        <i class="bi bi-list-check me-1"></i>
                                        查询到: <span class="fw-bold"><?php echo count($records); ?></span> 条记录
                                    </h6>
                                </div>
                            </div>
                            
                            <h6 class="mb-3 text-center"><i class="bi bi-funnel me-1"></i>状态筛选</h6>
                            <div class="row justify-content-center g-2">
                                <div class="col-auto">
                                    <input type="radio" class="btn-check" name="status" id="status-all" value="" autocomplete="off" <?php echo empty($statusFilter) ? 'checked' : ''; ?>>
                                    <label class="btn btn-outline-primary rounded-pill px-3" for="status-all">
                                        <i class="bi bi-grid-3x3 me-1"></i>全部
                                    </label>
                                </div>
                                <div class="col-auto">
                                    <input type="radio" class="btn-check" name="status" id="status-paid" value="paid" autocomplete="off" <?php echo $statusFilter === 'paid' ? 'checked' : ''; ?>>
                                    <label class="btn btn-outline-success rounded-pill px-3" for="status-paid">
                                        <i class="bi bi-check-circle me-1"></i>已支付
                                    </label>
                                </div>
                                <div class="col-auto">
                                    <input type="radio" class="btn-check" name="status" id="status-waiting" value="waiting" autocomplete="off" <?php echo $statusFilter === 'waiting' ? 'checked' : ''; ?>>
                                    <label class="btn btn-outline-warning rounded-pill px-3" for="status-waiting">
                                        <i class="bi bi-clock me-1"></i>未缴费
                                    </label>
                                </div>
                                <div class="col-auto">
                                    <input type="radio" class="btn-check" name="status" id="status-refunded" value="refunded" autocomplete="off" <?php echo $statusFilter === 'refunded' ? 'checked' : ''; ?>>
                                    <label class="btn btn-outline-danger rounded-pill px-3" for="status-refunded">
                                        <i class="bi bi-arrow-return-left me-1"></i>已退款
                                    </label>
                                </div>
                                <div class="col-auto">
                                    <input type="radio" class="btn-check" name="status" id="status-expired" value="expired" autocomplete="off" <?php echo $statusFilter === 'expired' ? 'checked' : ''; ?>>
                                    <label class="btn btn-outline-secondary rounded-pill px-3" for="status-expired">
                                        <i class="bi bi-exclamation-circle me-1"></i>过期未缴
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mt-4">
                        <div class="col-12 text-center">
                            <button type="submit" class="btn btn-primary me-3 rounded-pill px-4">
                                <i class="bi bi-filter me-1"></i>应用筛选
                            </button>
                            <button type="button" class="btn btn-outline-secondary rounded-pill px-4" onclick="clearAllFilters()">
                                <i class="bi bi-arrow-clockwise me-1"></i>重置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- 手势图标容器 -->
        <div id="hand-gesture-container" style="position: absolute; top: 0; left: 0; width: 100%; height: 0; pointer-events: none; z-index: 1000;"></div>
        
        <!-- 核心统计信息 - 两两一行布局 -->
        <div class="row mb-3">
            <!-- 第一行 -->
            <div class="col-6 mb-2">
                <div class="stats-card" id="stats-total-amount" style="background: linear-gradient(135deg, #007bff 0%, #0056b3 100%); color: white; cursor: pointer;" onclick="filterTotalAmount()">
                    <i class="bi bi-currency-yen"></i>
                    <div class="stats-number">¥<?php echo number_format($totalPaidAmount, 2); ?></div>
                    <div>总缴费金额</div>
                </div>
            </div>
            <div class="col-6 mb-2">
                <div class="stats-card active" id="stats-paid" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%); color: white; cursor: pointer;" onclick="filterByStatus('paid')">
                    <i class="bi bi-check-circle-fill"></i>
                    <div class="stats-number"><?php echo $totalPaidCount; ?> 笔</div>
                    <div>已支付</div>
                </div>
            </div>
            
            <!-- 第二行 -->
            <div class="col-6 mb-2">
                <div class="stats-card" id="stats-waiting" style="background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%); color: white; cursor: pointer;" onclick="filterWaiting()">
                    <i class="bi bi-clock-fill"></i>
                    <div class="stats-number"><?php echo $totalWaitingCount; ?> 笔</div>
                    <div>未缴费</div>
                </div>
            </div>
            <div class="col-6 mb-2">
                <div class="stats-card" id="stats-refunded" style="background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%); color: white; cursor: pointer;" onclick="filterByStatus('refunded')">
                    <i class="bi bi-arrow-return-left"></i>
                    <div class="stats-number"><?php echo $totalRefundedCount; ?> 笔</div>
                    <div>已退款</div>
                </div>
            </div>
            
            <!-- 第三行 -->
            <div class="col-6 mb-2">
                <div class="stats-card" id="stats-today-paid-amount" style="background: linear-gradient(135deg, #20c997 0%, #17a2b8 100%); color: white; cursor: pointer;" onclick="filterByDate('today', 'paid')">
                    <i class="bi bi-wallet2"></i>
                    <div class="stats-number">¥<?php echo number_format($todayPaidAmount, 2); ?></div>
                    <div>当日缴费金额</div>
                </div>
            </div>
            <div class="col-6 mb-2">
                <div class="stats-card" id="stats-today-refund-amount" style="background: linear-gradient(135deg, #fd7e14 0%, #ffc107 100%); color: white; cursor: pointer;" onclick="filterByDate('today', 'refund')">
                    <i class="bi bi-arrow-return-left"></i>
                    <div class="stats-number">¥<?php echo number_format($todayRefundAmount, 2); ?></div>
                    <div>当日退费金额</div>
                </div>
            </div>
            
            <!-- 第四行 - 新增统计卡片 -->
            <div class="col-6 mb-2">
                <div class="stats-card" id="stats-expired" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%); color: white; cursor: pointer;" onclick="filterExpired()">
                    <i class="bi bi-exclamation-circle-fill"></i>
                    <div class="stats-number"><?php echo $totalExpiredCount; ?> 笔</div>
                    <div>过期未缴</div>
                </div>
            </div>
            <div class="col-6 mb-2">
                <div class="stats-card" id="stats-total-refund-amount" style="background: linear-gradient(135deg, #343a40 0%, #212529 100%); color: white; cursor: pointer;" onclick="filterByStatus('refunded')">
                    <i class="bi bi-cash-coin"></i>
                    <div class="stats-number">¥<?php echo number_format($totalRefundAmount, 2); ?></div>
                    <div>总退款金额</div>
                </div>
            </div>
            
            <!-- 第五行 - 新增统计卡片 -->
            <div class="col-6 mb-2">
                <div class="stats-card" id="stats-today-signup" style="background: linear-gradient(135deg, #17a2b8 0%, #138496 100%); color: white; cursor: pointer;" onclick="filterByDate('today', 'signup')">
                    <i class="bi bi-person-plus-fill"></i>
                    <div class="stats-number"><?php echo $todaySignupCount; ?> 人</div>
                    <div>当日报名人数</div>
                </div>
            </div>
            <div class="col-6 mb-2">
                <div class="stats-card" id="stats-total-records" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%); color: white; cursor: pointer;" onclick="filterByStatus('all')">
                    <i class="bi bi-people-fill"></i>
                    <div class="stats-number"><?php echo $totalRecordsCount; ?> 笔</div>
                    <div>总记录数</div>
                </div>
            </div>
        </div>

        <!-- 最近10天统计图表 - 延迟加载 -->
        <div class="card mb-3" id="chart-section">
            <div class="card-header bg-gradient-primary text-white">
                <h6 class="mb-0"><i class="bi bi-graph-up me-1"></i>最近10天统计</h6>
            </div>
            <div class="card-body p-3">
                <div class="text-center py-4" id="chart-loading">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2 text-muted">图表数据加载中...</p>
                </div>
                <div class="chart-container mb-3" style="display: none;">
                    <canvas id="countChart"></canvas>
                </div>
                <div class="chart-container" style="display: none;">
                    <canvas id="amountChart"></canvas>
                </div>
                <div class="text-center mt-2" style="display: none;">
                    <small class="text-muted">
                        <i class="bi bi-info-circle me-1"></i>
                        统计周期: <?php echo date('m-d', strtotime('-9 days')); ?> ~ <?php echo date('m-d'); ?>
                    </small>
                </div>
            </div>
        </div>

        <!-- 缴费记录列表 -->
        <div class="card">
            <div class="card-header bg-gradient-primary text-white">
                <h6 class="mb-0"><i class="bi bi-list-check me-1"></i>缴费记录列表</h6>
            </div>
            <div class="card-body p-0">
                <!-- 查询结果列表标题 -->
                <div class="p-3 border-bottom bg-light">
                    <h5 class="mb-0 text-primary"><i class="bi bi-search me-2"></i>查询结果列表 <small class="text-muted">(共 <?php echo count($records); ?> 条记录)</small></h5>
                </div>

                <div class="table-responsive" style="overflow-x: auto; -webkit-overflow-scrolling: touch;">
                    <table class="table table-hover table-striped mb-0" style="min-width: 700px; white-space: nowrap;">
                        <thead class="table-dark">
                            <tr>
                                <th>序号</th>
                                <th class="mobile-time-show">时间</th>
                                <th>手机号</th>
                                <th>状态</th>
                                <th>金额</th>
                                <th>姓名</th>
                                <th>课程</th>
                                <th>身份证号</th>
                                <th>订单号</th>
                                <th>内部订单号</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($records)): ?>
                            <tr>
                                <td colspan="9" class="text-center py-4 text-muted">
                                    <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                                    暂无缴费记录
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php $index=1;$num=0; foreach ($records as $record): ?>
                            <tr>
                                <td class="mobile-time-show"><?php echo $index++;?></td>
                                <td class="mobile-time-show"><?php echo date('m-d H:i', strtotime($record['create_time'])); ?></td>
                                <td><?php echo htmlspecialchars($record['mobile']); ?></td>
                                <td>
                                    <?php if ($record['refund_status'] == 1 || $record['pay_status'] == 4): ?>
                                        <span class="badge bg-danger">已退款</span>
                                    <?php elseif ($record['pay_status'] == 1 && $record['refund_status'] == null): ?>
                                        <span class="badge bg-success">已支付</span>
                                    <?php elseif ($record['form_status'] == 0): ?>
                                        <span class="badge bg-warning text-dark">未缴费</span>
                                    <?php elseif ($record['form_status'] == 5): ?>
                                        <span class="badge bg-secondary">过期未缴</span>
                                    <?php else: ?>
                                        <span class="badge bg-info">未知</span>
                                    <?php endif; ?>
                                </td>
                                <td>¥<?php echo number_format($record['amount'], 2);$num=$num+$record['amount']; ?></td>
                                <td><?php echo htmlspecialchars($record['nickname'] ?: $record['username']); ?></td>
                                <td><?php echo htmlspecialchars($record['class_name'] ?: '未知课程'); ?></td>
                                <td class="id-card-column" style="font-family: 'Courier New', Monaco, monospace; letter-spacing: 0.5px;" title="<?php echo htmlspecialchars($record['id_card'] ?: ''); ?>"><?php echo htmlspecialchars($record['id_card'] ?: '-'); ?></td>
                                <td><?php echo htmlspecialchars($record['pay_channel_id'] ?: '-'); ?></td>
                                <td class="order-column" style="font-family: 'Courier New', Monaco, monospace; word-break: break-all;" title="<?php echo htmlspecialchars($record['order_id'] ?: ''); ?>"><?php echo htmlspecialchars($record['order_id'] ?: '-'); ?></td>
                            </tr>
                            <?php endforeach; ?>
                                <tr>
                                    <td class="mobile-time-show"></td>
                                    <td class="mobile-time-show"></td>
                                    <td></td>
                                    <td>

                                    </td>
                                    <td>合计：¥<?php echo number_format($num, 2); ?></td>
                                    <td></td>
                                    <td></td>
                                    <td class="id-card-column" style="font-family: 'Courier New', Monaco, monospace; letter-spacing: 0.5px;" title=""></td>
                                    <td></td>
                                    <td class="order-column" style="font-family: 'Courier New', Monaco, monospace; word-break: break-all;" title=""></td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- 导出和复制按钮 -->
                <div class="d-flex justify-content-center mt-3 gap-2">

                    <button class="btn btn-primary btn-sm" onclick="copyTable()">
                        <i class="bi bi-clipboard"></i> 复制表格
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 图表数据 - 自定义颜色配置
        const chartData = {
            labels: [<?php echo implode(', ', array_map(function($stat) { return '"' . date('m-d', strtotime($stat['date'])) . '"'; }, $last10DaysStats)); ?>],
            datasets: [
                {
                    label: '报名人数',
                    data: [<?php echo implode(', ', array_column($last10DaysStats, 'signup_count')); ?>],
                    borderColor: '#ffc107',  // 黄色 - 报名
                    backgroundColor: 'rgba(255, 193, 7, 0.1)',
                    tension: 0.4,
                    borderDash: [5, 5]  // 虚线样式
                },
                {
                    label: '缴费人数',
                    data: [<?php echo implode(', ', array_column($last10DaysStats, 'paid_count')); ?>],
                    borderColor: '#1e7e34',  // 深绿色 - 缴费
                    backgroundColor: 'rgba(30, 126, 52, 0.1)',
                    tension: 0.4
                },
                {
                    label: '退费人数',
                    data: [<?php echo implode(', ', array_column($last10DaysStats, 'refund_count')); ?>],
                    borderColor: '#ff0000',  // 灰色 - 退款
                    backgroundColor: 'rgba(108, 117, 125, 0.1)',
                    tension: 0.4
                }
            ]
        };

        const amountChartData = {
            labels: [<?php echo implode(', ', array_map(function($stat) { return '"' . date('m-d', strtotime($stat['date'])) . '"'; }, $last10DaysStats)); ?>],
            datasets: [
                {
                    label: '报名金额',
                    data: [<?php echo implode(', ', array_column($last10DaysStats, 'signup_amount')); ?>],
                    borderColor: '#ffc107',  // 黄色 - 报名
                    backgroundColor: 'rgba(255, 193, 7, 0.1)',
                    tension: 0.4,
                    borderDash: [5, 5]  // 虚线样式
                },
                {
                    label: '缴费金额',
                    data: [<?php echo implode(', ', array_column($last10DaysStats, 'paid_amount')); ?>],
                    borderColor: '#1e7e34',  // 深绿色 - 缴费
                    backgroundColor: 'rgba(30, 126, 52, 0.1)',
                    tension: 0.4
                },
                {
                    label: '退费金额',
                    data: [<?php echo implode(', ', array_column($last10DaysStats, 'refund_amount')); ?>],
                    borderColor: '#ff0000',  // 灰色 - 退款
                    backgroundColor: 'rgba(108, 117, 125, 0.1)',
                    tension: 0.4
                }
            ]
        };

        // 初始化图表
        function initializeCharts() {
            // 检查 Chart.js 是否可用
            if (typeof Chart === 'undefined') {
                console.error('Chart.js 未加载，跳过图表初始化');
                return;
            }
            
            // 获取图表画布元素
            const countChartElement = document.getElementById('countChart');
            const amountChartElement = document.getElementById('amountChart');
            
            if (!countChartElement || !amountChartElement) {
                console.error('图表画布元素未找到');
                return;
            }
            
            try {
                // 人数统计图表
                const countCtx = countChartElement.getContext('2d');
                new Chart(countCtx, {
                    type: 'line',
                    data: chartData,
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: {
                                    boxWidth: 12,
                                    font: {
                                        size: 10
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    font: {
                                        size: 9
                                    }
                                }
                            },
                            x: {
                                ticks: {
                                    font: {
                                        size: 9
                                    }
                                }
                            }
                        }
                    }
                });

                // 金额统计图表
                const amountCtx = amountChartElement.getContext('2d');
                new Chart(amountCtx, {
                    type: 'line',
                    data: amountChartData,
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: {
                                    boxWidth: 12,
                                    font: {
                                        size: 10
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    font: {
                                        size: 9
                                    },
                                    callback: function(value) {
                                        return '¥' + value;
                                    }
                                }
                            },
                            x: {
                                ticks: {
                                    font: {
                                        size: 9
                                    }
                                }
                            }
                        }
                    }
                });
                
                console.log('图表初始化成功');
            } catch (error) {
                console.error('图表初始化失败:', error);
            }
        }

        // 显示加载动画
        function showChartLoading() {
            const chartContainer = document.getElementById('chart-container');
            if (chartContainer && !chartContainer.querySelector('.loading-spinner')) {
                const spinner = document.createElement('div');
                spinner.className = 'loading-spinner';
                spinner.innerHTML = '<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div>';
                chartContainer.appendChild(spinner);
            }
        }

        // 隐藏加载动画
        function hideChartLoading() {
            const chartContainer = document.getElementById('chart-container');
            if (chartContainer) {
                const spinner = chartContainer.querySelector('.loading-spinner');
                if (spinner) {
                    chartContainer.removeChild(spinner);
                }
            }
        }

        // 清除日期并重置
        function clearDateAndReset() {
            const form = document.getElementById('filterForm');
            const dateInput = form.querySelector('input[name="start_date"]');
            dateInput.value = '';
            
            // 创建隐藏字段来标识清除日期操作
            const clearDateInput = document.createElement('input');
            clearDateInput.type = 'hidden';
            clearDateInput.name = 'clear_date';
            clearDateInput.value = '1';
            form.appendChild(clearDateInput);
            
            form.submit();
        }

        // 清除所有筛选条件
        function clearAllFilters() {
            const form = document.getElementById('filterForm');
            form.reset();
            
            // 移除所有单选按钮的选中状态
            const radioButtons = form.querySelectorAll('input[type="radio"]');
            radioButtons.forEach(radio => {
                radio.checked = false;
            });
            
            // 提交表单
            form.submit();
        }

        // 搜索功能
        document.getElementById('searchInput').addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const rows = document.querySelectorAll('tbody tr');
            
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                if (text.includes(searchTerm)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        });

        // 统计卡片点击筛选函数 - 直接提交对应参数，不考虑表单筛选条件
        function filterByStatus(status) {
            // 显示加载状态
            showChartLoading();
            
            // 移除所有统计卡片的active类
            document.querySelectorAll('.stats-card').forEach(card => {
                card.classList.remove('active');
            });
            
            // 根据状态为对应的统计卡片添加active类
            const statusCardMap = {
                'paid': 'stats-paid',
                'waiting': 'stats-waiting', 
                'refunded': 'stats-refunded',
                'expired': 'stats-expired'
            };
            
            if (statusCardMap[status]) {
                const targetCard = document.getElementById(statusCardMap[status]);
                if (targetCard) {
                    targetCard.classList.add('active');
                }
            }
            
            // 获取当前所有筛选条件
            const searchValue = document.getElementById('searchInput').value;
            const startDate = document.querySelector('input[name="start_date"]').value;
            
            // 通过AJAX加载对应状态的数据，同时保留其他筛选条件
            const params = new URLSearchParams({
                status: status,
                search: searchValue,
                start_date: startDate,
                ajax: 1
            });
            
            fetch('?' + params.toString())
                .then(response => response.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    
                    // 更新表格内容
                    const newTbody = doc.querySelector('tbody');
                    if (newTbody) {
                        document.querySelector('tbody').innerHTML = newTbody.innerHTML;
                    }
                    
                    // 更新统计信息
                    updateStatsDisplay(doc);
                    
                    // 更新状态筛选按钮状态
                    updateStatusFilterState(status);
                    
                    // 隐藏加载状态
                    hideChartLoading();
                })
                .catch(error => {
                    console.error('加载数据失败:', error);
                    hideChartLoading();
                });
        }
        
        // 过期未缴特殊筛选 - 相当于点击过期未缴状态，但清空日期和其他条件
        function filterExpired() {
            // 显示加载状态
            showChartLoading();
            
            // 移除所有统计卡片的active类
            document.querySelectorAll('.stats-card').forEach(card => {
                card.classList.remove('active');
            });
            
            // 为过期未缴统计卡片添加active类
            const expiredCard = document.getElementById('stats-expired');
            if (expiredCard) {
                expiredCard.classList.add('active');
            }
            
            // 清空搜索框
            document.getElementById('searchInput').value = '';
            
            // 清空日期输入框
            document.querySelector('input[name="start_date"]').value = '';
            
            // 通过AJAX加载过期未缴状态的数据，不保留其他筛选条件
            const params = new URLSearchParams({
                status: 'expired',
                search: '',
                start_date: '',
                ajax: 1
            });
            
            fetch('?' + params.toString())
                .then(response => response.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    
                    // 更新表格内容
                    const newTbody = doc.querySelector('tbody');
                    if (newTbody) {
                        document.querySelector('tbody').innerHTML = newTbody.innerHTML;
                    }
                    
                    // 更新统计信息
                    updateStatsDisplay(doc);
                    
                    // 更新状态筛选按钮状态
                    updateStatusFilterState('expired');
                    
                    // 隐藏加载状态
                    hideChartLoading();
                })
                .catch(error => {
                    console.error('加载数据失败:', error);
                    hideChartLoading();
                });
        }
        
        function filterByDate(dateType, actionType) {
            // 显示加载状态
            showChartLoading();
            
            // 获取当前所有筛选条件
            const searchValue = document.getElementById('searchInput').value;
            const currentStatus = document.querySelector('input[name="status"]:checked').value;
            
            const params = new URLSearchParams({
                search: searchValue,
                status: currentStatus,
                ajax: 1
            });
            
            // 设置日期筛选
            if (dateType === 'today') {
                const today = new Date();
                const todayStr = today.toISOString().split('T')[0];
                params.set('start_date', todayStr);
            }
            
            // 设置状态筛选
            if (actionType === 'paid') {
                params.set('status', 'paid');
            } else if (actionType === 'refund') {
                params.set('status', 'refunded');
            } else if (actionType === 'signup') {
                // 报名人数不需要状态筛选
                params.delete('status');
            }
            
            // 通过AJAX加载数据
            fetch('?' + params.toString())
                .then(response => response.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    
                    // 更新表格内容
                    const newTbody = doc.querySelector('tbody');
                    if (newTbody) {
                        document.querySelector('tbody').innerHTML = newTbody.innerHTML;
                    }
                    
                    // 更新统计信息
                    updateStatsDisplay(doc);
                    
                    // 更新日期输入框显示
                    updateDateInputDisplay(dateType);
                    
                    // 隐藏加载状态
                    hideChartLoading();
                })
                .catch(error => {
                    console.error('加载数据失败:', error);
                    hideChartLoading();
                });
        }
        
        // 更新统计信息显示
        function updateStatsDisplay(doc) {
            // 从返回的文档中提取统计信息并更新页面显示
            const statsElements = doc.querySelectorAll('.stats-card .stats-number');
            if (statsElements.length > 0) {
                // 更新页面上的统计卡片显示
                const currentStatsElements = document.querySelectorAll('.stats-card .stats-number');
                statsElements.forEach((element, index) => {
                    if (currentStatsElements[index]) {
                        currentStatsElements[index].textContent = element.textContent;
                    }
                });
            }
            
            // 更新查询结果标题
            const resultTitle = doc.querySelector('.p-3.border-bottom.bg-light h5');
            if (resultTitle) {
                document.querySelector('.p-3.border-bottom.bg-light h5').textContent = resultTitle.textContent;
            }
        }
        
        // 更新状态筛选按钮状态
        function updateStatusFilterState(status) {
            const statusRadios = document.querySelectorAll('input[name="status"]');
            statusRadios.forEach(radio => {
                if (radio.value === status) {
                    radio.checked = true;
                }
            });
        }
        
        // 更新日期输入框显示
        function updateDateInputDisplay(dateType) {
            const dateInput = document.querySelector('input[name="start_date"]');
            if (dateType === 'today') {
                const today = new Date();
                const todayStr = today.toISOString().split('T')[0];
                dateInput.value = todayStr;
            }
        }
        
        // 总缴费金额特殊筛选 - 相当于点击已支付，但清空日期和其他条件
        function filterTotalAmount() {
            // 显示加载状态
            showChartLoading();
            
            // 移除所有统计卡片的active类
            document.querySelectorAll('.stats-card').forEach(card => {
                card.classList.remove('active');
            });
            
            // 为已支付统计卡片添加active类
            const paidCard = document.getElementById('stats-paid');
            if (paidCard) {
                paidCard.classList.add('active');
            }
            
            // 清空搜索框
            document.getElementById('searchInput').value = '';
            
            // 清空日期输入框
            document.querySelector('input[name="start_date"]').value = '';
            
            // 通过AJAX加载已支付状态的数据，不保留其他筛选条件
            const params = new URLSearchParams({
                status: 'paid',
                search: '',
                start_date: '',
                ajax: 1
            });
            
            fetch('?' + params.toString())
                .then(response => response.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    
                    // 更新表格内容
                    const newTbody = doc.querySelector('tbody');
                    if (newTbody) {
                        document.querySelector('tbody').innerHTML = newTbody.innerHTML;
                    }
                    
                    // 更新统计信息
                    updateStatsDisplay(doc);
                    
                    // 更新状态筛选按钮状态
                    updateStatusFilterState('paid');
                    
                    // 隐藏加载状态
                    hideChartLoading();
                })
                .catch(error => {
                    console.error('加载数据失败:', error);
                    hideChartLoading();
                });
        }
        
        // 未缴费特殊筛选 - 相当于点击未缴费状态，但清空日期和其他条件
        function filterWaiting() {
            // 显示加载状态
            showChartLoading();
            
            // 移除所有统计卡片的active类
            document.querySelectorAll('.stats-card').forEach(card => {
                card.classList.remove('active');
            });
            
            // 为未缴费统计卡片添加active类
            const waitingCard = document.getElementById('stats-waiting');
            if (waitingCard) {
                waitingCard.classList.add('active');
            }
            
            // 清空搜索框
            document.getElementById('searchInput').value = '';
            
            // 清空日期输入框
            document.querySelector('input[name="start_date"]').value = '';
            
            // 通过AJAX加载未缴费状态的数据，不保留其他筛选条件
            const params = new URLSearchParams({
                status: 'waiting',
                search: '',
                start_date: '',
                ajax: 1
            });
            
            fetch('?' + params.toString())
                .then(response => response.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    
                    // 更新表格内容
                    const newTbody = doc.querySelector('tbody');
                    if (newTbody) {
                        document.querySelector('tbody').innerHTML = newTbody.innerHTML;
                    }
                    
                    // 更新统计信息
                    updateStatsDisplay(doc);
                    
                    // 更新状态筛选按钮状态
                    updateStatusFilterState('waiting');
                    
                    // 隐藏加载状态
                    hideChartLoading();
                })
                .catch(error => {
                    console.error('加载数据失败:', error);
                    hideChartLoading();
                });
        }
        
        // 无限滚动加载
        let isLoading = false;
        let currentPage = <?php echo $page; ?>;
        let hasMore = <?php echo $page < $totalPages ? 'true' : 'false'; ?>;
        
        function initInfiniteScroll() {
            const observer = new IntersectionObserver((entries) => {
                if (entries[0].isIntersecting && !isLoading && hasMore) {
                    loadMoreRecords();
                }
            }, { threshold: 0.1 });
            
            const sentinel = document.createElement('div');
            sentinel.id = 'scroll-sentinel';
            sentinel.style.height = '50px';
            document.querySelector('.table-responsive').appendChild(sentinel);
            observer.observe(sentinel);
        }
        
        function loadMoreRecords() {
            if (isLoading || !hasMore) return;
            
            isLoading = true;
            currentPage++;
            
            const searchValue = document.getElementById('searchInput').value;
            const statusFilter = document.querySelector('input[name="status"]:checked').value;
            const startDate = document.querySelector('input[name="start_date"]').value;
            
            const params = new URLSearchParams({
                search: searchValue,
                status: statusFilter,
                start_date: startDate,
                page: currentPage,
                ajax: 1
            });
            
            fetch('?' + params.toString())
                .then(response => response.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    const newRecords = doc.querySelectorAll('tbody tr');
                    
                    if (newRecords.length > 0) {
                        const tbody = document.querySelector('tbody');
                        newRecords.forEach(record => {
                            tbody.appendChild(record);
                        });
                        
                        // 更新是否有更多数据
                        hasMore = currentPage < <?php echo $totalPages; ?>;
                    } else {
                        hasMore = false;
                    }
                    
                    isLoading = false;
                })
                .catch(error => {
                    console.error('加载更多记录失败:', error);
                    isLoading = false;
                });
        }
        
        // 初始化无限滚动
        initInfiniteScroll();

        // 状态筛选按钮变化事件
        document.querySelectorAll('input[name="status"]').forEach(radio => {
            radio.addEventListener('change', function() {
                showChartLoading();
                document.getElementById('filterForm').submit();
            });
        });

        // 延迟加载图表 - 当图表进入视口时加载
        function lazyLoadCharts() {
            const chartSection = document.getElementById('chart-section');
            
            // 检查是否支持IntersectionObserver
            if ('IntersectionObserver' in window) {
                const observer = new IntersectionObserver((entries) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            // 图表进入视口，开始加载
                            loadCharts();
                            observer.unobserve(chartSection);
                        }
                    });
                }, { threshold: 0.1 });

                observer.observe(chartSection);
            } else {
                // 如果不支持IntersectionObserver，延迟5秒加载，确保Chart.js完全加载
                setTimeout(loadCharts, 5000);
            }
        }

        // 实际加载图表的函数
        function loadCharts() {
            setTimeout(() => {
                // 检查 Chart.js 是否可用
                if (typeof Chart === 'undefined') {
                    console.error('Chart.js 未加载，跳过图表加载');
                    // 隐藏加载提示
                    document.getElementById('chart-loading').style.display = 'none';
                    return;
                }
                
                try {
                    initializeCharts();
                    // 隐藏加载提示，显示图表
                    document.getElementById('chart-loading').style.display = 'none';
                    document.querySelectorAll('.chart-container, .text-center.mt-2').forEach(el => {
                        el.style.display = '';
                    });
                } catch (error) {
                    console.error('图表加载失败:', error);
                    // 即使图表加载失败也要隐藏加载提示
                    document.getElementById('chart-loading').style.display = 'none';
                }
            }, 1000); // 增加延迟到1000ms，确保Chart.js完全加载
        }

        // 数据缓存
        let chartDataCache = null;
        let amountChartDataCache = null;
        
        // 页面加载完成后初始化触摸事件和延迟加载
        document.addEventListener('DOMContentLoaded', function() {
            // 记录页面加载时间
            const loadTime = performance.now();
            console.log('页面DOM加载完成时间:', loadTime.toFixed(2) + 'ms');
            
            // 使用requestIdleCallback进行非关键任务调度
            if ('requestIdleCallback' in window) {
                requestIdleCallback(() => {
                    // 先加载其他内容，延迟加载图表
                    lazyLoadCharts();
                });
            } else {
                // 不支持requestIdleCallback时使用setTimeout，延迟3秒确保Chart.js加载
                setTimeout(() => {
                    lazyLoadCharts();
                }, 3000);
            }
            
            // 使用事件委托优化触摸事件
            document.body.addEventListener('touchstart', function(e) {
                if (e.target.classList.contains('btn')) {
                    e.target.classList.add('active');
                }
            });
            
            document.body.addEventListener('touchend', function(e) {
                if (e.target.classList.contains('btn')) {
                    e.target.classList.remove('active');
                }
            });
            
            // 性能监控
            const observer = new PerformanceObserver((list) => {
                list.getEntries().forEach((entry) => {
                    console.log(`${entry.name}: ${entry.startTime.toFixed(2)}ms`);
                });
            });
            observer.observe({ entryTypes: ['measure'] });
        });

        // 移动端优化：防止双击缩放
        let lastTouchEnd = 0;
        document.addEventListener('touchend', function(event) {
            const now = new Date().getTime();
            if (now - lastTouchEnd <= 300) {
                event.preventDefault();
            }
            lastTouchEnd = now;
        }, false);

        // 图片懒加载
        if ('IntersectionObserver' in window) {
            const imageObserver = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        img.src = img.dataset.src;
                        imageObserver.unobserve(img);
                    }
                });
            });
            
            document.querySelectorAll('img[data-src]').forEach(img => {
                imageObserver.observe(img);
            });
        }

        // 注册Service Worker（如果支持）- 移除注册以避免404错误
        // if ('serviceWorker' in navigator) {
        //     navigator.serviceWorker.register('/sw.js')
        //         .then(registration => {
        //             console.log('Service Worker 注册成功:', registration);
        //         })
        //         .catch(error => {
        //             console.log('Service Worker 注册失败:', error);
        //         });
        // }

        // 资源预加载优化 - 修正预加载逻辑
        const criticalResources = [
            'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
            'https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css'
        ];
        
        criticalResources.forEach(resource => {
            const link = document.createElement('link');
            link.rel = 'preload';
            link.href = resource;
            link.as = 'style';
            link.onload = function() {
                this.rel = 'stylesheet';
            };
            document.head.appendChild(link);
        });
        
        // 手势图标功能
        function initHandGesture() {
            const statsCards = [
                'stats-total-amount',    // 总缴费金额
                'stats-paid',            // 已支付
                'stats-waiting',          // 未缴费
                'stats-refunded',         // 已退款
                'stats-today-paid-amount', // 当日缴费金额
                'stats-today-refund-amount', // 当日退费金额
                'stats-expired',          // 过期未缴
                'stats-total-refund-amount', // 总退款金额
                'stats-today-signup',     // 当日报名人数
                'stats-total-records'     // 总记录数
            ];
            
            // 创建手势图标
            const handGesture = document.createElement('div');
            handGesture.className = 'hand-gesture';
            handGesture.innerHTML = '👆';
            handGesture.id = 'hand-gesture';
            document.getElementById('hand-gesture-container').appendChild(handGesture);
            
            // 获取第一个统计卡片的位置
            const firstCard = document.getElementById(statsCards[0]);
            if (firstCard) {
                const rect = firstCard.getBoundingClientRect();
                const containerRect = document.getElementById('hand-gesture-container').getBoundingClientRect();
                
                // 计算相对于手势容器的位置
                // 向下调整一个卡片高度（约100px）
                const relativeTop = rect.top - containerRect.top - 35 + 100;
                const relativeLeft = rect.left - containerRect.left + rect.width / 2 - 12;
                
                handGesture.style.top = relativeTop + 'px';
                handGesture.style.left = relativeLeft + 'px';
                
                console.log(`手图初始位置`);
                console.log(`容器位置: top=${containerRect.top}, left=${containerRect.left}`);
                console.log(`卡片位置: top=${rect.top}, left=${rect.left}, width=${rect.width}, height=${rect.height}`);
                console.log(`相对位置: top=${relativeTop}, left=${relativeLeft}`);
            }
            
            // 检查是否有已点击的选项卡（从localStorage获取）
            const clickedTab = localStorage.getItem('lastClickedTab');
            if (clickedTab && statsCards.includes(clickedTab)) {
                moveHandToCard(clickedTab);
            }
            
            // 为所有统计卡片添加点击事件
            statsCards.forEach(cardId => {
                const card = document.getElementById(cardId);
                if (card) {
                    card.addEventListener('click', function() {
                        // 保存点击的选项卡
                        localStorage.setItem('lastClickedTab', cardId);
                        // 移动手势图标到当前卡片
                        moveHandToCard(cardId);
                        // 添加点击动画
                        handGesture.style.animation = 'handClick 0.6s';
                        setTimeout(() => {
                            handGesture.style.animation = 'handPulse 1.5s infinite';
                        }, 600);
                    });
                }
            });
        }
        
        function moveHandToCard(cardId) {
            const handGesture = document.getElementById('hand-gesture');
            const card = document.getElementById(cardId);
            
            if (handGesture && card) {
                const rect = card.getBoundingClientRect();
                const containerRect = document.getElementById('hand-gesture-container').getBoundingClientRect();
                
                // 计算相对于手势容器的位置
                // 计算相对于手势容器的位置
                // 向下调整一个卡片高度（约100px）
                const relativeTop = rect.top - containerRect.top - 35 + 100;
                const relativeLeft = rect.left - containerRect.left + rect.width / 2 - 12;
                
                handGesture.style.top = relativeTop + 'px';
                handGesture.style.left = relativeLeft + 'px';
                
                console.log(`手图移动到卡片: ${cardId}`);
                console.log(`容器位置: top=${containerRect.top}, left=${containerRect.left}`);
                console.log(`卡片位置: top=${rect.top}, left=${rect.left}, width=${rect.width}, height=${rect.height}`);
                console.log(`相对位置: top=${relativeTop}, left=${relativeLeft}`);
            }
        }
        
        // 初始化手势图标
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                console.log('初始化手图功能...');
                initHandGesture();
                
                // 添加滚动事件监听器，确保手图在滚动时保持正确位置
                window.addEventListener('scroll', function() {
                    const handGesture = document.getElementById('hand-gesture');
                    const lastClickedTab = localStorage.getItem('lastClickedTab');
                    if (handGesture && lastClickedTab) {
                        moveHandToCard(lastClickedTab);
                    }
                });
                
                // 添加窗口大小改变事件监听器
                window.addEventListener('resize', function() {
                    const handGesture = document.getElementById('hand-gesture');
                    const lastClickedTab = localStorage.getItem('lastClickedTab');
                    if (handGesture && lastClickedTab) {
                        moveHandToCard(lastClickedTab);
                    }
                });
                
            }, 1000); // 延迟1秒显示手势图标
        });
        
        // 导出Excel功能
        function exportToExcel() {
            // 引入SheetJS库
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js';
            script.onload = function() {
                // 获取表格数据
                const table = document.querySelector('.table');
                if (table) {
                    // 获取搜索关键词用于文件名
                    const searchInput = document.getElementById('searchInput');
                    const searchValue = searchInput ? searchInput.value : '';
                    // 获取当前日期
                    const now = new Date();
                    const year = now.getFullYear();
                    const month = String(now.getMonth() + 1).padStart(2, '0');
                    const day = String(now.getDate()).padStart(2, '0');
                    const currentDate = `${year}${month}${day}`;
                    const filename = searchValue ? `${searchValue}课程报名缴费记录${currentDate}.xlsx` : `课程报名缴费记录${currentDate}.xlsx`;
                    
                    // 格式化函数：确保身份证号完整显示
                    function formatIdCard(value) {
                        if (!value) return value;
                        const stringValue = value.toString().trim();
                        // 如果是18位身份证号，确保完整保留，不做任何格式化
                        if (/^\d{17}[\dXx]$/.test(stringValue) || /^\d{18}$/.test(stringValue)) {
                            return stringValue; // 返回原始完整号码，不做任何处理
                        }
                        // 对于其他纯数字，可以添加空格格式化
                        if (/^\d+$/.test(stringValue)) {
                            return stringValue.replace(/(\d{4})/g, '$1 ').trim();
                        }
                        return stringValue;
                    }
                    
                    // 使用SheetJS创建工作表
                    const ws = XLSX.utils.table_to_sheet(table, {sheet: "缴费统计"});
                    
                    // 设置身份证号和订单号为文本格式
                    const range = XLSX.utils.decode_range(ws['!ref']);
                    // 存储需要设置为文本格式的列索引
                    const textColumns = [];
                    
                    // 首先遍历表头行，找出身份证号和订单号列
                    for (let C = range.s.c; C <= range.e.c; ++C) {
                        const headerCell = ws[XLSX.utils.encode_cell({c: C, r: 0})];
                        if (headerCell) {
                            const headerValue = headerCell.v;
                            if (headerValue && (headerValue.includes('身份证') || headerValue.includes('订单'))) {
                                textColumns.push(C);
                            }
                        }
                    }
                    
                    // 遍历所有数据行，对指定列设置文本格式
                    for (let R = range.s.r; R <= range.e.r; ++R) {
                        for (let C of textColumns) {
                            const cell_address = XLSX.utils.encode_cell({c: C, r: R});
                            if (ws[cell_address]) {
                                // 设置单元格格式为文本
                                ws[cell_address].z = '@';
                                // 对于数据行，确保数值被当作文本处理
                                if (R > 0 && (typeof ws[cell_address].v === 'number' || typeof ws[cell_address].v === 'string')) {
                                    // 确保身份证号完整显示，不被格式化
                                    const formattedValue = formatIdCard(ws[cell_address].v);
                                    // 使用单引号前缀确保Excel将其视为文本，避免科学计数法
                                    ws[cell_address].v = "'" + formattedValue;
                                    // 添加t属性确保单元格类型为字符串
                                    ws[cell_address].t = 's';
                                }
                            }
                        }
                    }
                    
                    // 创建工作簿
                    const wb = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(wb, ws, "缴费统计");
                    
                    // 导出文件
                    XLSX.writeFile(wb, filename);
                } else {
                    alert('未找到表格数据');
                }
            };
            document.head.appendChild(script);
        }
        
        // 导出表格到Excel功能
        function exportTableToExcel() {
            // 引入SheetJS库
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js';
            script.onload = function() {
                // 获取表格数据
                const table = document.querySelector('.table-responsive table');
                if (table) {
                    // 获取搜索关键词用于文件名
                    const searchInput = document.getElementById('searchInput');
                    const searchValue = searchInput ? searchInput.value : '';
                    // 获取当前日期
                    const now = new Date();
                    const year = now.getFullYear();
                    const month = String(now.getMonth() + 1).padStart(2, '0');
                    const day = String(now.getDate()).padStart(2, '0');
                    const currentDate = `${year}${month}${day}`;
                    const filename = searchValue ? `《${searchValue}课程报名缴费记录${currentDate}》.xlsx` : `《课程报名缴费记录${currentDate}》.xlsx`;
                    
                    // 格式化函数：确保身份证号完整显示
                    function formatIdCard(value) {
                        if (!value) return value;
                        const stringValue = value.toString().trim();
                        // 如果是18位身份证号，确保完整保留，不做任何格式化
                        if (/^\d{17}[\dXx]$/.test(stringValue) || /^\d{18}$/.test(stringValue)) {
                            return stringValue; // 返回原始完整号码，不做任何处理
                        }
                        // 对于其他纯数字，可以添加空格格式化
                        if (/^\d+$/.test(stringValue)) {
                            return stringValue.replace(/(\d{4})/g, '$1 ').trim();
                        }
                        return stringValue;
                    }
                    
                    // 使用SheetJS创建工作表
                    const ws = XLSX.utils.table_to_sheet(table, {sheet: "缴费统计"});
                    
                    // 设置身份证号和订单号为文本格式
                    const range = XLSX.utils.decode_range(ws['!ref']);
                    // 存储需要设置为文本格式的列索引
                    const textColumns = [];
                    
                    // 首先遍历表头行，找出身份证号和订单号列
                    for (let C = range.s.c; C <= range.e.c; ++C) {
                        const headerCell = ws[XLSX.utils.encode_cell({c: C, r: 0})];
                        if (headerCell) {
                            const headerValue = headerCell.v;
                            if (headerValue && (headerValue.includes('身份证') || headerValue.includes('订单'))) {
                                textColumns.push(C);
                            }
                        }
                    }
                    
                    // 遍历所有数据行，对指定列设置文本格式
                    for (let R = range.s.r; R <= range.e.r; ++R) {
                        for (let C of textColumns) {
                            const cell_address = XLSX.utils.encode_cell({c: C, r: R});
                            if (ws[cell_address]) {
                                // 设置单元格格式为文本
                                ws[cell_address].z = '@';
                                // 对于数据行，确保数值被当作文本处理
                                if (R > 0 && (typeof ws[cell_address].v === 'number' || typeof ws[cell_address].v === 'string')) {
                                    // 确保身份证号完整显示，不被格式化
                            const formattedValue = formatIdCard(ws[cell_address].v);
                            // 使用单引号前缀确保Excel将其视为文本，避免科学计数法
                            ws[cell_address].v = "'" + formattedValue;
                                    // 添加t属性确保单元格类型为字符串
                                    ws[cell_address].t = 's';
                                }
                            }
                        }
                    }
                    
                    // 创建工作簿
                    const wb = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(wb, ws, "缴费统计");
                    
                    // 导出文件
                    XLSX.writeFile(wb, filename);
                } else {
                    alert('未找到表格数据');
                }
            };
            document.head.appendChild(script);
        }
        
        // 复制表格功能
        function copyTable() {
            // 获取表格元素
            const table = document.querySelector('.table-responsive table');
            if (!table) {
                alert('未找到表格数据');
                return;
            }
            
            // 创建临时文本区域用于复制
            const textArea = document.createElement('textarea');
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            
            // 构建表格文本
            let text = '';
            const rows = table.querySelectorAll('tr');
            
            rows.forEach((row, rowIndex) => {
                const cells = row.querySelectorAll('th, td');
                const rowData = [];
                
                cells.forEach(cell => {
                    // 移除HTML标签，只保留文本内容
                    const cellText = cell.textContent.trim();
                    rowData.push(cellText);
                });
                
                text += rowData.join('\t') + '\n';
            });
            
            // 设置文本区域内容
            textArea.value = text;
            
            // 选择并复制文本
            textArea.select();
            document.execCommand('copy');
            
            // 移除临时文本区域
            document.body.removeChild(textArea);
            
            // 提示用户
            alert('表格数据已复制到剪贴板');
        }
    </script>
    

    <!-- 身份证号显示优化样式 -->
    <style>
        /* 身份证号列样式 - 防止数字显示异常 */
        .id-card-column {
            font-family: 'Courier New', Monaco, 'Lucida Console', monospace !important;
            letter-spacing: 0.5px;
            word-break: break-all;
            white-space: normal;
            min-width: 180px;
            max-width: 200px;
        }
        
        /* 响应式表格优化 */
        @media (max-width: 768px) {
            .id-card-column {
                font-size: 12px;
                min-width: 160px;
                max-width: 180px;
            }
        }
        
        /* 表格单元格优化 */
        .table-responsive td {
            padding: 8px 6px;
            vertical-align: middle;
        }
        
        /* 防止长数字被科学计数法显示 */
        .table-responsive td[style*="id-card-column"] {
            text-align: left;
            direction: ltr;
        }
        
        /* 订单号列同样处理 */
        .order-column {
            font-family: 'Courier New', Monaco, 'Lucida Console', monospace !important;
            word-break: break-all;
            white-space: normal;
            min-width: 120px;
        }
    </style>

    <script>
        // 页面加载完成后优化身份证号显示
        document.addEventListener('DOMContentLoaded', function() {
            // 找到所有包含身份证号的单元格
            const idCardCells = document.querySelectorAll('td:nth-child(6)'); // 假设身份证号在第6列
            idCardCells.forEach(cell => {
                const text = cell.textContent.trim();
                // 检查是否为18位身份证号
                if (/^\d{17}[\dXx]$|^\d{18}$/.test(text)) {
                    cell.classList.add('id-card-column');
                    // 确保显示完整号码
                    cell.setAttribute('title', text);
                }
            });
            
            // 同样处理订单号列（第8列）
            const orderCells = document.querySelectorAll('td:nth-child(8)');
            orderCells.forEach(cell => {
                const text = cell.textContent.trim();
                if (text && text.length > 10) {
                    cell.classList.add('order-column');
                    cell.setAttribute('title', text);
                }
            });
        });
    </script>
</body>
</html>